package com.offcn.filters;

import com.offcn.common.utils.JWTUtil;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

/**
 * 验证token
 */
public class JwtChectGatewayFilterFactory extends AbstractGatewayFilterFactory<JwtChectGatewayFilterFactory.Config> {

    //内部类
    public static class Config{
    }


    public JwtChectGatewayFilterFactory(){
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchenge,chain)->{
            String jwtToken = exchenge.getRequest().getHeaders().getFirst("Authorization");
            //校验token的合法性
            if (null != jwtToken){  //jwtToken正常情况下（不为空）
                boolean verifyResult = JWTUtil.verify(jwtToken);
                if (!verifyResult){//校验失败 --> token不合法,响应未登录异常
                    ServerHttpResponse response = exchenge.getResponse();
                    //设置响应头
                    HttpHeaders headers = response.getHeaders();
                    headers.add("Content-Type","application/json;charset=utf-8");
                    headers.add("Cache-Control","no-store,no-cache,must-revalidata,max-age=0");   //不在浏览器进行缓存而在redis进行缓存
                    //设置响应体
                    String warningString = "token验证失败";
                    DataBuffer dataBuffer = response.bufferFactory().wrap(warningString.getBytes());
                    return response.writeWith(Mono.just(dataBuffer));
                }
                //token是正常的话
                return chain.filter(exchenge);
            }
            //jwtToken不正常
            ServerHttpResponse response = exchenge.getResponse();
            //设置响应头
            HttpHeaders headers = response.getHeaders();
            headers.add("Content-Type","application/json;charset=utf-8");
            headers.add("Cache-Control","no-store,no-cache,must-revalidata,max-age=0");
            //设置响应体
            String warningString = "未登录或登录超时";
            DataBuffer dataBuffer = response.bufferFactory().wrap(warningString.getBytes());
            return response.writeWith(Mono.just(dataBuffer));
        };
    }



}
